//
//  MainModule.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-5.
//
//

#import "MainModule.h"
#import <chameleon-ios-sdk/ChamleonSDK.h>

#import "MainUtils.h"
#import "IsolatedStorageFile.h"

#import "DataCenter.h"


#import "SplashViewController.h"

#define NOTPROMISS      1
#define SERVER_ERROR    2
#define APP_UPDATE      3
#define ROLE_PRIVILIGES 5

/*
 业务逻辑：
 1,复制www目录
 2,应用验证
 3,应用版本检测
 4,角色权限获取
 5,成功后发送通知，并签到应用
*/
@interface MainModule()<UIAlertViewDelegate,ZillaDelegate>

//获取用户角色
-(void)rolesList;

//应用签到
-(void)registerDevice;

@end

@implementation MainModule

-(id)init{
    self=[super init];
    
    if(self){
        
        zillaSDK=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
        zillaSDK.delegate=self;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerDevice) name:@"CubeAuth_Success" object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerDevice) name:@"CubeAuthSync_Success" object:nil];
    }
    
    return self;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(UIViewController*)startMainViewControllerWithParams:(NSDictionary*)dict{
    return [[SplashViewController alloc] init];
}

- (BOOL)application:(CApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
    return YES;
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken{
    
    NSString *token = [[_deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    [DataCenter defaultCenter].deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
}

-(void)startDispatchAsync{
    [IsolatedStorageFile copyFolderAtPath:[IsolatedStorageFile cordovaResourceDirectory] toPath:[IsolatedStorageFile cordovaRootDirectory] error:nil];
}

-(void)finishDispatchAsync{
    [zillaSDK checkAppVaildate];
}

-(void)rolesList{
    //获取用户角色
    [zillaSDK rolePriviligesList:[DataCenter defaultCenter].username];
}


//应用签到
-(void)registerDevice{
    [zillaSDK registerDevice:[DataCenter defaultCenter].deviceToken accountName:[DataCenter defaultCenter].username roleName:[DataCenter defaultCenter].rolePriviligeModel.rolesName];
    
}


#pragma mark zilla delegate

//应用验证成功
-(void)authorSuccess{
    [zillaSDK checkAppVersion];
}

//应用验证失败
-(void)authorFailed:(int)statusCode errorMessage:(NSString *)errorMessage{
    
    if(statusCode==403 || statusCode==400){
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"应用没有授于权限" message:nil delegate:self cancelButtonTitle:@"退出" otherButtonTitles:nil, nil];
        alertView.tag=NOTPROMISS;
        [alertView show];
    }
    else{
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"服务器异常，请重试" message:nil delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"重试", nil];
        alertView.tag=SERVER_ERROR;
        [alertView show];
    }
}

//应用版本回调
-(void)appVersionChecked:(AppInfoModel*)appInfoModel{
    int newBuild = appInfoModel.build;
    int currentBuild = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] intValue];
    if (newBuild > currentBuild){
        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        [DataCenter defaultCenter].plist=appInfoModel.plist;
        NSString *message = [NSString stringWithFormat:@"当前版本:%@\n最新版本:%@\n版本说明:\n%@", currentVersion, appInfoModel.version, appInfoModel.releaseNote];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[ NSString stringWithFormat:@"%@平台版本更新",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] ] message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
        alertView.tag=APP_UPDATE;
        [alertView show];
    }
    else{
        
        //获取用户角色
        [self rolesList];
    }
}

-(void)appVersionFailed:(int)statusCode errorMessage:(NSString*)errorMessage{
    //获取用户角色
    [self rolesList];

}

//设备签到回调
-(void)registerDeviceFinish:(BOOL)success{
    NSLog(@"device is register %@",(success?@"success":@"failed"));
}

//回执权限获取回调
-(void)rolePriviligesListSuccess:(RolePriviligeModel*)rolePriviligeModel{
    [DataCenter defaultCenter].guestRolePriviligeModel=rolePriviligeModel;
    [DataCenter defaultCenter].rolePriviligeModel=rolePriviligeModel;
    
    //成功后，向主界面回调
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MainModule_LoadFinish" object:nil];
    
    [self registerDevice];
    
}

-(void)rolePriviligesListFailed:(int)statusCode errorMessage:(NSString*)errorMessage{
    if(statusCode==403 || statusCode==400){
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"应用没有授于权限" message:nil delegate:self cancelButtonTitle:@"退出" otherButtonTitles:nil, nil];
        alertView.tag=NOTPROMISS;
        [alertView show];
    }
    else{
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"服务器异常，请重试" message:nil delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"重试", nil];
        alertView.tag=ROLE_PRIVILIGES;
        [alertView show];
    }
    
}


#pragma mark alertview delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag== SERVER_ERROR){
        if(buttonIndex==1)
            [zillaSDK checkAppVaildate];
        else
            exit(0);
    }
    else if(alertView.tag==ROLE_PRIVILIGES){
        if(buttonIndex==1)
            [self rolesList];
        else
            exit(0);

    }
    else if(alertView.tag==APP_UPDATE){
        if(buttonIndex==1){
            NSString* downloadUrl=[zillaSDK.zillaUrlScheme attachmentByAIdWithNoAppKey:[DataCenter defaultCenter].plist ];
            NSURL* url=[zillaSDK.zillaUrlScheme applicationNewVersionLink:downloadUrl];
            [[UIApplication sharedApplication] openURL:url];
        }
        else{
            //获取用户角色
            [self rolesList];
            
        }
    }
    else if(alertView.tag==NOTPROMISS){
        exit(0);
    }
}





@end








